from __future__ import annotations

import json
import os
import textwrap
from pathlib import Path
from typing import Iterable


QUESTIONS_PATH = Path(os.environ.get("AGENT_INTERVIEW_QUESTIONS", "data/interview_questions.json"))


def load_questions(path: Path | None = None) -> dict[str, list[str]]:
    target = path or QUESTIONS_PATH
    if not target.exists():
        raise FileNotFoundError(f"Interview question file not found: {target}")
    data = json.loads(target.read_text(encoding="utf-8"))
    if not isinstance(data, dict):
        raise ValueError("Interview questions must be stored as a JSON object")
    normalized: dict[str, list[str]] = {}
    for category, questions in data.items():
        if not isinstance(questions, list) or not all(isinstance(q, str) for q in questions):
            raise ValueError(f"Invalid question list for category '{category}'")
        normalized[str(category)] = [str(q).strip() for q in questions if str(q).strip()]
    return normalized


def build_interview_prompt(
    *,
    agent_profile: dict[str, object],
    categories: Iterable[str] | None = None,
    limit_per_category: int = 5,
    questions_path: Path | None = None,
) -> str:
    question_bank = load_questions(questions_path)
    selected_categories = list(categories) if categories else list(question_bank.keys())
    agent_name = agent_profile.get("name", agent_profile.get("id", "the agent"))
    role = agent_profile.get("role", "agent")
    objectives = ", ".join(agent_profile.get("objectives", []) or []) or "(none listed)"
    agent_id = agent_profile.get("id", "unknown")
    lines = [
        f"You are interviewing {agent_name} ({role}).",
        f"Agent ID: {agent_id}",
        "Focus on coherence between self-knowledge, memory, planning, reactions, and reflections.",
        f"Current objectives: {objectives}.",
        "For each question, evaluate whether the response matches the agent's prior commitments.",
    ]
    for category in selected_categories:
        questions = question_bank.get(category, [])
        if not questions:
            continue
        lines.append(f"\n[{category.replace('_', ' ').title()}]")
        for question in questions[:limit_per_category]:
            lines.append(f"- {question}")
    prompt = "\n".join(lines)
    return textwrap.dedent(prompt).strip()
